package org.lewis.man.controllers;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lewis.common.ip.IPSeeker;
import org.lewis.common.utils.WebUtils;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.tocersoft.framework.core.annotations.Controller;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.web.annotations.Mapping;
import com.tocersoft.framework.web.renderer.ImageRenderer;
import com.tocersoft.framework.web.renderer.Renderer;
import com.tocersoft.framework.web.renderer.TemplateRenderer;

/**
 * 前台公共
 * 
 * @author taiqichao
 * 
 */
@Controller
public class HomeController {

	private static final String VIEWBASEPATH = "/WEB-INF/views/common";

	Log log=LogFactory.getLog(HomeController.class);
	
	@Injection
	private IPSeeker ips;
	
	
	@Mapping("/")
	public Renderer index() throws Exception {
		String ip = WebUtils.getIpAddr();
		String country=ips.getCountry(ip);
		Map<String, Object> data=new HashMap<String, Object>();
		data.put("country", country);
		return new TemplateRenderer(VIEWBASEPATH + "/index.vm",data);
	}
	
	@Mapping("/captcha")
	public Renderer captcha()throws Exception{
		DefaultKaptcha captchaProducer=new DefaultKaptcha();
		Properties properties=new Properties();
		properties.put("kaptcha.image.width", 210);
		properties.put("kaptcha.image.border", 0);
		Config config=new Config(properties);
		captchaProducer.setConfig(config);
		String capText = captchaProducer.createText();
		WebUtils.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		return new ImageRenderer(bi);
	}
	
	@Mapping("/error")
	public Renderer error() throws Exception {
		return new TemplateRenderer(VIEWBASEPATH + "/error_page.vm");
	}

}
